<template>
  <div class="app-container">
    <PageHeader back-text="返回" back-type="back" :title="contractInfo.contractName || '加载中...'" />

    <ContractDetail :contract-info="contractInfo" />

    <el-card class="box-card project-audit-card mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <span class="font-bold">项目列表</span>
          </div>
          <div class="flex items-center">
            <ProjectStatusDisplay label="项目审核状态" :status-options="approval_commit_status" :status-value="contractInfo.proStatus" />
          </div>
        </div>
      </template>

      <!-- 项目展示表格 -->
      <el-table v-loading="loading" :data="projectList" border row-key="id" class="project-table">
        <!-- 序号 -->
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <!-- 项目名称 -->
        <el-table-column label="项目名称" align="center" prop="proName" width="300" show-overflow-tooltip />

        <!-- 项目编号 -->
        <el-table-column label="项目编号" align="center" prop="proNumber" width="120" show-overflow-tooltip />

        <!-- 业主单位 -->
        <el-table-column label="业主单位" align="center" prop="ownerUnit" width="100" show-overflow-tooltip />

        <!-- 项目类型 -->
        <el-table-column label="项目类型" align="center" prop="proType" width="100">
          <template #default="scope">
            <dict-tag :options="project_type" :value="scope.row.proType" />
          </template>
        </el-table-column>

        <!-- 工作内容 -->
        <el-table-column label="工作内容" align="left" prop="proContent" width="400" show-overflow-tooltip />

        <!-- 执行总裁 -->
        <el-table-column label="执行总裁" align="center" prop="proPresidentsName" width="120" show-overflow-tooltip />

        <!-- 项目负责人 -->
        <el-table-column label="项目负责人" align="center" prop="proLeadersName" width="120" show-overflow-tooltip />

        <!-- 项目金额 -->
        <el-table-column label="项目金额" align="center" prop="proAmount" width="150">
          <template #default="scope">
            <span v-if="scope.row.proAmount">
              {{
                Number(scope.row.proAmount).toLocaleString('zh-CN', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
              }}元
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 项目金额备注 -->
        <el-table-column label="项目金额备注" align="center" prop="proAmountRemark" width="200" show-overflow-tooltip />

        <!-- 项目状态 -->
        <el-table-column label="项目状态" align="center" prop="proStatus" width="90">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.proStatus" />
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />

        <!-- 创建人 -->
        <el-table-column label="创建人" align="center" prop="createBy" width="120" />

        <!-- 创建时间 -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template #default="scope">
            {{ scope.row.createTime ? scope.row.createTime : '-' }}
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="回款节点" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button plain type="primary" size="small" @click="showReceiveNodes(scope.row)" v-hasPermi="['project:receive:list']">
              回款节点
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="暂无项目数据" />
        </template>
      </el-table>

      <!-- 底部信息容器 - 使用组件 -->
      <ProjectBottomInfo :project-list="projectList" />
    </el-card>

    <!-- 审核操作组件 -->
    <AuditAction v-if="checkContractStatus(contractInfo.contractStatus)" :loading="auditLoading" @audit="handleAuditAction" />

    <!-- 回款节点对话框 -->
    <el-dialog v-model="receiveNodesDialogVisible" :title="`${currentProject?.proName || ''} - 回款节点`" width="900px" :close-on-click-modal="false">
      <el-table v-loading="receiveNodesLoading" :data="receiveNodesList" border style="width: 100%" max-height="400">
        <el-table-column label="付款节点" prop="nodeTitle" width="500" align="left">
          <template #default="scope">
            <span>{{ scope.row.nodeTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收款负责人" prop="nodeLeadersName" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.nodeLeadersName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="备注" prop="remark" width="200" align="center">
          <template #default="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无回款节点数据" />
        </template>
      </el-table>

      <!-- 汇总信息 -->
      <div v-if="receiveNodesList.length > 0" class="mt-4 p-4 bg-gray-50 rounded-lg">
        <div class="flex flex-wrap gap-6">
          <div class="flex items-center">
            <span class="text-sm text-gray-600 mr-2">节点总金额：</span>
            <span class="font-semibold text-green-600"
              >{{
                getTotalAmount().toLocaleString('zh-CN', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
              }}元</span
            >
          </div>
          <div class="flex items-center" v-if="currentProject?.proAmount">
            <span class="text-sm text-gray-600 mr-2">项目总金额：</span>
            <span class="font-semibold text-blue-600"
              >{{
                Number(currentProject.proAmount).toLocaleString('zh-CN', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
              }}元</span
            >
          </div>
          <div class="flex items-center" v-if="currentProject?.proAmount">
            <span class="text-sm text-gray-600 mr-2">剩余金额：</span>
            <span class="font-semibold text-red-600"
              >{{
                (Number(currentProject.proAmount) - getTotalAmount()).toLocaleString('zh-CN', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
              }}元</span
            >
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="receiveNodesDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getProContract } from '@/api/project/init/contract';
import { listProInfo } from '@/api/project/init/proInfo';
import { audit } from '@/api/other/approval/index';
import type { ApprovalAuditBo } from '@/api/other/approval/types';
import ContractDetail from '../../components/ContractDetail.vue';
import type { ProContractVO } from '@/api/project/init/contract/types';
import { getReceiveMoneyNodesByProId } from '@/api/project/receive/index';
import type { ProReceiveMoneyVO } from '@/api/project/receive/types';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import AuditAction from '@/components/AuditAction/index.vue';
import ProjectBottomInfo from '@/views/project/components/ProjectBottomInfo.vue';
import { checkContractStatus } from '@/utils/permission';

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const { project_type, contract_status, approval_commit_status } = toRefs<any>(
  proxy?.useDict('project_type', 'contract_status', 'approval_commit_status')
);

// 合同信息
const contractInfo = ref<ProContractVO & { proStatus?: string }>({} as ProContractVO);

// 项目列表
const projectList = ref([]);
const loading = ref(false);

// 审核加载状态
const auditLoading = ref(false);

// 回款节点相关
const receiveNodesDialogVisible = ref(false);
const receiveNodesList = ref<ProReceiveMoneyVO[]>([]);
const receiveNodesLoading = ref(false);
const currentProject = ref<any>(null);

// 获取合同信息
const getContract = async (contractId) => {
  try {
    const res = await getProContract(contractId);
    if (res.data) {
      contractInfo.value = res.data;
    }
  } catch (error) {
    console.error('获取合同详情失败:', error);
    proxy?.$modal.msgError('获取合同详情失败');
  }
};

// 获取项目列表
const getProjectList = async (contractId) => {
  loading.value = true;
  try {
    const params: any = { contractId };
    const res = await listProInfo(params);
    projectList.value = res.data || [];
  } catch (error) {
    console.error('获取项目列表失败:', error);
    proxy?.$modal.msgError('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

// 显示回款节点
const showReceiveNodes = async (project: any) => {
  currentProject.value = project;
  receiveNodesDialogVisible.value = true;
  receiveNodesLoading.value = true;

  try {
    const res = await getReceiveMoneyNodesByProId(project.id);
    receiveNodesList.value = res.data || [];
  } catch (error) {
    console.error('获取回款节点失败:', error);
    ElMessage.error('获取回款节点失败');
    receiveNodesList.value = [];
  } finally {
    receiveNodesLoading.value = false;
  }
};

// 计算总金额
const getTotalAmount = () => {
  return receiveNodesList.value.reduce((total, node) => {
    return total + (Number(node.totalAmount) || 0);
  }, 0);
};

// 计算已收金额
const getReceivedAmount = () => {
  return receiveNodesList.value.reduce((total, node) => {
    return total + (Number(node.receivedAmount) || 0);
  }, 0);
};

// 计算剩余金额
const getSurplusAmount = () => {
  return receiveNodesList.value.reduce((total, node) => {
    return total + (Number(node.surplusAmount) || 0);
  }, 0);
};

// 审核操作处理
const handleAuditAction = (data: { status: string; idea: string }) => {
  auditLoading.value = true;
  const auditData: ApprovalAuditBo = {
    businessId: contractInfo.value.id,
    businessType: 'CONTRACT-SPLIT-PROJECT',
    status: data.status,
    idea: data.idea
  };

  audit(auditData)
    .then(() => {
      proxy?.$modal.msgSuccess('审核成功');
      router.push('/project/init/audit');
    })
    .catch(() => {
      auditLoading.value = false;
    });
};

onMounted(async () => {
  const contractId = route.params.contractId;
  if (contractId) {
    try {
      await Promise.all([getContract(contractId), getProjectList(contractId)]);
    } catch (error) {
      console.error('初始化数据失败:', error);
      proxy?.$modal.msgError('加载数据失败，请刷新页面重试');
    }
  } else {
    proxy?.$modal.msgError('缺少合同ID参数');
    router.push('/project/init/audit');
  }
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-descriptions {
  margin-bottom: 10px;
}

/* 项目表格样式 */
.project-table {
  width: 100%;
}

.project-table :deep(.el-table__cell) {
  padding: 8px 0;
}

/* 卡片样式统一 */
.project-audit-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.audit-action-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

/* 文本溢出处理 */
.text-overflow {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: top;
}

/* 回款节点对话框样式 */
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    padding: 12px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 回款节点表格样式 */
:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }

  .el-tag {
    font-weight: 500;
  }
}

/* 汇总信息样式 */
.bg-gray-50 {
  background-color: #f9fafb;
}

.rounded-lg {
  border-radius: 8px;
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-600 {
  color: #16a34a;
}

.text-orange-600 {
  color: #ea580c;
}

.text-red-600 {
  color: #dc2626;
}

.text-gray-600 {
  color: #4b5563;
}

.font-semibold {
  font-weight: 600;
}

.flex {
  display: flex;
}

.flex-wrap {
  flex-wrap: wrap;
}

.items-center {
  align-items: center;
}

.gap-6 {
  gap: 1.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.p-4 {
  padding: 1rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  /* 移动端对话框调整 */
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }
}
</style>
